package com.icesoft.core.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES对称加密和解密
 * aes-256-ecb
 */

public class AesUtil {
	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
	private static final String AES_TRANSFORMATION = "AES/ECB/PKCS5Padding";

	/**
	 * AES加密，转base64
	 * 
	 * @param content
	 *            待加密的内容
	 * @param key，
	 *            必须是16或32位 加密密钥
	 * @return 加密后的密文
	 */
	public static String encrypt(String key, String content) throws IllegalArgumentException {
		if (StringUtils.isBlank(content)) {
			return content;
		}
		return encrypt(getSecretKeySpec(key), content);

	}

	public static String encrypt(SecretKeySpec keySpec, String content) throws IllegalArgumentException {
		byte[] data = encrypt(keySpec, content.getBytes(DEFAULT_ENCODING));
		return Base64.getEncoder().encodeToString(data);
	}

	public static byte[] encrypt(SecretKeySpec keySpec, byte[] data) throws IllegalArgumentException {
		Cipher cipher = CipherUtils.getCipher(AES_TRANSFORMATION, keySpec, Cipher.ENCRYPT_MODE);
		return CipherUtils.doFinal(cipher, data);
	}

	/**
	 * 转base64，AES解密
	 * 
	 * @param content
	 *            待解密的密文
	 * @param key，必须是16或32位
	 *            解密密钥
	 * @return 解密后的String
	 */
	public static String decrypt(String key, String content) throws IllegalArgumentException {
		if (StringUtils.isBlank(content)) {
			return content;
		}
		return decrypt(getSecretKeySpec(key), content);

	}

	public static String decrypt(SecretKeySpec keySpec, String content) throws IllegalArgumentException {
		byte[] encryptBytes = Base64.getDecoder().decode(content.getBytes(DEFAULT_ENCODING));
		byte[] decryptBytes = decrypt(keySpec, encryptBytes);
		return new String(decryptBytes, DEFAULT_ENCODING);
	}

	public static byte[] decrypt(SecretKeySpec keySpec, byte[] data) throws IllegalArgumentException {
		Cipher cipher = CipherUtils.getCipher(AES_TRANSFORMATION, keySpec, Cipher.DECRYPT_MODE);
		return CipherUtils.doFinal(cipher, data);
	}

	public static SecretKeySpec getSecretKeySpec(String key) {
		byte[] keyByte = key.getBytes(DEFAULT_ENCODING);
		int length = keyByte.length;
		if (length != 16 && length != 32) {
			throw new IllegalArgumentException("key必须是16位或32位：" + key);
		}
		return new SecretKeySpec(keyByte, "AES");
	}

}
